/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.obffinder.filters;

import com.openbookformat.page.PagesManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import org.openbookformat.obffinder.FindResult;
import org.openbookformat.tags.TagParsingException;
import org.openide.cookies.EditorCookie;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.lookup.ServiceProvider;

/**
 *
 * @author matamh0a
 */
@ServiceProvider(service=Filter.class)
public class FootnotesFixerFilter extends FindReplaceFilter {
    
    public FootnotesFixerFilter() {
        name = "Footnote Associator";
        findText = "<custom_code>";
        replaceText = "<custom_code>";
        regExp = true;
        ignoreCase = false;
        useVariables = false;
        useIgonreNewLine = true;
        applyToAll = true;
        description = "Associate footnote marks with footnote"
                + " text.";
        chapters = new ArrayList<DataObject>();
    }
    
    @Override
    public Map<DataObject, ArrayList<FindResult>> find() {
        Map<DataObject, ArrayList<FindResult>> findResult
                = new HashMap<DataObject, ArrayList<FindResult>>();

        EditorCookie ed = null;
        PagesManager manager = null;
        ArrayList<FindResult> r = null;
        ArrayList<FindResult> tmp = null;
        for (int k = 0; k < chapters.size(); k++) {             
            r = new ArrayList<FindResult>();
            ed = chapters.get(k).getCookie(EditorCookie.class);
            try {
                manager = new PagesManager(ed);
            } catch (TagParsingException ex) {
                Exceptions.printStackTrace(ex);
            }
            int firstPage = manager.getFirstPageNumber();
            int lastPage = manager.getLastPageNumber();
            for(int i = firstPage; i <= lastPage; i++) {
                tmp = manager.associateFootnotes(i);
                for(int j = 0; j < tmp.size(); j++) {
                    r.add(tmp.get(j));
                }
            }
            findResult.put(chapters.get(k), r);
        }
        return findResult;
    }

}
